from fastapi import APIRouter, Request, HTTPException
from typing import Optional

from service.facebook_downloader_service import FacebookDownloaderService
from mrouter.domain.WxCloudRunHeader import WxCloudRunHeader
from utils.response import create_response
from config.logging_config import ProjectLoggers
from dto.facebook_request import FacebookInfoRequest, FacebookUrlRequest, FacebookMultiQualityRequest
from dto.facebook_response import (
    FacebookInfoResponse, FacebookDownloadUrlResponse, FacebookMultiQualityResponse,
    FacebookSupportedQualitiesResponse, FacebookUrlTypesResponse
)

logger = ProjectLoggers.get_service_logger()
router = APIRouter(prefix="/facebook", tags=["Facebook视频下载"])

# 创建服务实例
facebook_service = FacebookDownloaderService()

@router.post("/info", response_model=FacebookInfoResponse)
async def get_facebook_video_info(
    request: Request,
    info_request: FacebookInfoRequest
):
    """
    获取Facebook视频信息
    
    - **facebook_url**: Facebook视频链接
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取Facebook视频信息: {info_request.facebook_url}")
        
        # 调用服务获取视频信息
        result = await facebook_service.get_video_info(info_request.facebook_url)
        
        if result["success"]:
            logger.info(f"成功获取Facebook视频信息: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取视频信息",
                data=result["data"]
            )
        else:
            logger.warning(f"获取Facebook视频信息失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"Facebook视频信息请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取Facebook视频信息接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/download-url", response_model=FacebookDownloadUrlResponse)
async def get_facebook_download_url(
    request: Request,
    url_request: FacebookUrlRequest
):
    """
    获取Facebook视频直接下载链接
    
    - **facebook_url**: Facebook视频链接
    - **quality**: 视频质量（360p, 480p, 720p, 1080p, best, worst）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取Facebook下载链接: {url_request.facebook_url}, 质量: {url_request.quality}")
        
        # 调用服务获取下载链接
        result = await facebook_service.get_download_urls(
            facebook_url=url_request.facebook_url,
            quality=url_request.quality
        )
        
        if result["success"]:
            logger.info(f"成功获取Facebook下载链接: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取下载链接",
                data=result["data"]
            )
        else:
            logger.warning(f"获取Facebook下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"Facebook下载链接请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取Facebook下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/multi-quality-urls", response_model=FacebookMultiQualityResponse)
async def get_facebook_multi_quality_urls(
    request: Request,
    multi_request: FacebookMultiQualityRequest
):
    """
    获取Facebook视频多种质量的下载链接
    
    - **facebook_url**: Facebook视频链接
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取Facebook多质量下载链接: {multi_request.facebook_url}")
        
        # 调用服务获取多质量下载链接
        result = await facebook_service.get_multiple_quality_urls(multi_request.facebook_url)
        
        if result["success"]:
            logger.info(f"成功获取Facebook多质量下载链接: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取多质量下载链接",
                data=result["data"]
            )
        else:
            logger.warning(f"获取Facebook多质量下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"Facebook多质量下载链接请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取Facebook多质量下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/qualities", response_model=FacebookSupportedQualitiesResponse)
async def get_supported_qualities():
    """
    获取支持的视频质量选项
    """
    try:
        qualities = ["360p", "480p", "720p", "1080p", "best", "worst"]
        
        result = {
            "qualities": qualities,
            "default_quality": "best",
            "description": "360p-1080p为固定分辨率，best为最佳质量，worst为最低质量。Facebook视频质量取决于原视频。"
        }
        
        return create_response(
            code=200,
            msg="获取支持的质量选项成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取支持质量选项接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/url-types", response_model=FacebookUrlTypesResponse)
async def get_supported_url_types():
    """
    获取支持的Facebook URL类型
    """
    try:
        url_types = [
            {
                "type": "Facebook Watch",
                "pattern": "/watch/?v=VIDEO_ID",
                "description": "标准Facebook视频观看页面"
            },
            {
                "type": "Direct Video",
                "pattern": "/username/videos/VIDEO_ID/",
                "description": "用户页面的直接视频链接"
            },
            {
                "type": "Post Video",
                "pattern": "/username/posts/POST_ID",
                "description": "帖子中包含的视频"
            },
            {
                "type": "Facebook Reels",
                "pattern": "/reel/REEL_ID",
                "description": "Facebook短视频Reels"
            }
        ]
        
        examples = {
            "watch": "https://www.facebook.com/watch/?v=4100227806929329",
            "video": "https://www.facebook.com/username/videos/1234567890/",
            "post": "https://www.facebook.com/username/posts/1234567890",
            "reel": "https://www.facebook.com/reel/1234567890"
        }
        
        result = {
            "url_types": url_types,
            "examples": examples,
            "description": "支持多种Facebook视频URL格式，包括Watch页面、直接视频链接、帖子视频和Reels"
        }
        
        return create_response(
            code=200,
            msg="获取支持的URL类型成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取支持URL类型接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/quick-url")
async def quick_get_facebook_url(
    request: Request,
    facebook_url: str,
    quality: Optional[str] = "best"
):
    """
    快速获取Facebook视频下载链接（简化接口）
    
    - **facebook_url**: Facebook视频链接
    - **quality**: 视频质量，默认best
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 快速获取Facebook下载链接: {facebook_url}")
        
        # 验证Facebook URL
        if not facebook_url:
            return create_response(code=400, msg="Facebook链接不能为空")
        
        # 简单验证Facebook链接
        valid_domains = ['facebook.com', 'www.facebook.com', 'm.facebook.com', 'fb.com', 'fb.watch']
        if not any(domain in facebook_url for domain in valid_domains):
            return create_response(code=400, msg="请提供有效的Facebook链接")
        
        # 检查是否包含视频相关路径
        video_patterns = ['/watch/', '/videos/', '/posts/', '/reel/']
        if not any(pattern in facebook_url for pattern in video_patterns):
            return create_response(code=400, msg="链接必须包含视频内容")
        
        # 调用服务获取下载链接
        result = await facebook_service.get_download_urls(
            facebook_url=facebook_url,
            quality=quality or "best"
        )
        
        if result["success"]:
            data = result["data"]
            response_data = {
                "title": data["title"],
                "download_url": data["download_url"],
                "uploader": data.get("uploader"),
                "format": data["format"],
                "resolution": data["resolution"],
                "duration": data.get("duration"),
                "thumbnail": data.get("thumbnail")
            }
            
            logger.info(f"快速获取Facebook下载链接成功: {data['title']}")
            return create_response(
                code=200,
                msg="成功获取下载链接",
                data=response_data
            )
        else:
            logger.warning(f"快速获取Facebook下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except Exception as e:
        logger.error(f"快速获取Facebook下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}") 